from fastapi import FastAPI, File, UploadFile, Request
from fastapi.responses import HTMLResponse
import requests

app = FastAPI()


def upload_file(pre_signed_url, file):
    try:
        # 设置请求头
        headers = {
            "X-bailian-extra": "MTE0NTU2NDE3NjI2MTQyOA==",
            "Content-Type": "application/msword"
        }

        # 上传文件
        response = requests.put(pre_signed_url, data=file.file, headers=headers)

        # 检查响应状态码
        if response.status_code == 200:
            return "File uploaded successfully."
        else:
            return f"Failed to upload the file. ResponseCode: {response.status_code}"

    except Exception as e:
        return f"An error occurred: {str(e)}"


@app.get("/", response_class=HTMLResponse)
async def index():
    return '''
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>File Upload</title>
        </head>
        <body>
            <form method="post" enctype="multipart/form-data">
                <input type="file" name="file">
                <input type="submit" value="Upload">
            </form>
        </body>
        </html>
    '''


@app.post("/")
async def upload(file: UploadFile = File(...)):
    pre_signed_url = "https://dashscope-file-datacenter-prod-01.oss-cn-beijing.aliyuncs.com/1145564176261428/10329720/c376b053633f427d9b06230c061b8298.1745242200261.docx?Expires=1745248200&OSSAccessKeyId=LTAI5tFEd57BcgTFgxpSL5j1&Signature=ESzZk2BBmKOYOWhI6joZnuz%2FzWg%3D"
    result = upload_file(pre_signed_url, file)
    return result

    